﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ObstacleDragAndDrop : MonoBehaviour {
	// === Unity ======================================================================================================
	public GameObject GameObjectDragAndDrop;

	private void Start() {
		_camera = MapEditorBaseData.GetInstance.Camera.camera;
	}

	private void Update() {
		if (GameObjectDragAndDrop == null) {
			return;
		}
		var pos = _camera.ScreenToWorldPoint(Input.mousePosition);
		var normPos = Normalize(pos);
		GameObjectDragAndDrop.transform.position = normPos;

		if (!Input.GetMouseButton(InputConstants.MOUSE_BUTTON_LEFT)) {
			_createdObstacles.Clear();
			return;
		}
		if (Enumerable.Contains(_createdObstacles, normPos)) {
			return;
		}
		var go = (GameObject)Instantiate(GameObjectDragAndDrop);
		var color = go.renderer.material.color;
		go.renderer.material.color = new Color(color.r, color.g, color.b, 1f);
		_createdObstacles.Add(normPos);
	}

	// === Private ====================================================================================================
	private Camera _camera;
	private readonly List<Vector3> _createdObstacles = new List<Vector3>();


	private Vector3 Normalize(Vector3 position) {
		return new Vector3 {
			x = Point(position.x),
			y = 0,
			z = Point(position.z)
		};
	}

	private int Point(float position) {
		var point = (int) position;
		if (!(Math.Abs(position) - Math.Abs(point) > .5f)) {
			return point;
		}
		if (position < 0) {
			return point - 1;
		}
		return point + 1;
	}
}